home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / nihcl-30.lha / nihcl-3.0 / ex / ex5-6.c < prev    next >
C/C++ Source or Header  |  1990-05-29  |  1KB  |  43 lines

  1. // ex5-6.c -- String substitution
  2.  
  3. // $Header: /afs/alw.nih.gov/unix/sun4_40c/usr/local/src/nihcl-3.0/share/ex/RCS/ex5-6.c,v 3.0 90/05/29 14:34:15 kgorlen Rel $
  4.  
  5. #include "ExString.h"
  6.  
  7. String replace(const String& target,
  8.                 const String& oldss,
  9.                 const String& newss)
  10. {
  11.     if (oldss.length() == 0) return target;     // if old is empty
  12.     String result(target.capacity());
  13.     unsigned i=0;       // start position for
  14.                         // next substring comparison
  15.     unsigned j=0;       // start position of
  16.                         // last unmatched substring
  17.     while (i+oldss.length() <= target.length()) {
  18.         if (target(i,oldss.length()) == oldss) {
  19.             result &= target(j,i-j) & newss;
  20.             j = i += oldss.length();
  21.         }
  22.         else i++;
  23.     }
  24.     if (j != target.length())
  25.         result &= target(j,target.length()-j);
  26.     return result;
  27. }
  28.  
  29. main()
  30. {
  31.     String orig, substr, replacement;
  32.     while (1) {
  33.         cout << "Enter target string: ";  cin >> orig;
  34.         if (cin.eof()) break;
  35.         cout << "    Replace: ";  cin >> substr;
  36.         cout << "    With: ";  cin >> replacement;
  37.         cout << "    replace(" << orig << ',' << substr << ','
  38.              << replacement << ") = ";
  39.         cout << replace(orig, substr, replacement) << endl;
  40.     }
  41.     cout << endl;
  42. }
  43.